//
//  TSCreateMsgViewController.m
//  chart
//
//  Created by xu on 15/7/29.
//  Copyright (c) 2015年 xu. All rights reserved.
//

#import "TSCreateMsgViewController.h"
#import "TSCreateMsgTableView.h"
#import "TSMutipleCheckTableViewController.h"
#import "TSMsgModel.h"
#import "TSMsgContentItemCell.h"
#import "TSMsgDatePickerTextFieldCell.h"
#import "TSPickerViewTextFieldCell.h"
#import "TSMsgModel.h"
#import "TSEditContentController.h"


@implementation TSCreateMsgViewController{
    UIView * container;
    TSCreateMsgTableView *tableView;
    TSMsgModel *msgModel;
}

@synthesize msgId,enclosurePath;

- (void)viewDidLoad
{
    [super viewDidLoad];
    msgModel = [[TSMsgModel alloc] init];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(presentViewController:) name:TSNotification_PresentViewController object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectedEnclosure:) name:TSNotification_Selected_Enclosure object:nil];
    self.title = msgId?@"修改消息":@"创建消息";
    WS(weakSelf);
    [self rightBarButtonWithTitle:@"发送" barNorImage:nil barHltImage:nil action:^{
        if (!weakSelf) {
            return;
        }
        [weakSelf createMsg];
    }];
    
    tableView = [[TSCreateMsgTableView alloc] initWithFrame:CGRectMake(0, 0, currentDeviceWidth, currentDeviceHeight-NAV_AND_STATUS_BAR_HEIGHT)];
    
    [self.view addSubview:tableView];
    
    if (msgId) {
        msgModel.requestParams = @{TSDictionaryKeyDefine_Id:msgId};
        [msgModel fetchWithPath:kRequestUrl_SendMessage_outOne_messageinfo completionHandler:^(BOOL isSucceeded, NSError *error) {
            if (!weakSelf) {
                return;
            }
            
            __strong typeof (weakSelf)strongSelf = weakSelf;
            
            strongSelf->tableView.msgModel = strongSelf->msgModel;
            [strongSelf->tableView reloadData];
        } NoProgress:NO];
    }
    else{
        [self leftBarButtonWithTitle:nil barNorImage:[UIImage imageNamed:@"nav_dark_close"] barHltImage:nil action:^{
            if (!weakSelf) {
                return;
            }
            [weakSelf dismissViewControllerAnimated:YES completion:nil];
        }];
    }
}

/* 创建并发送消息 */
- (void)createMsg
{
    if(![self checkCanSend]){return;}
    
    if (msgId) {
        [self updateMsg];
    }
    else{
        [self insertMsg];
    }
}

-(BOOL)checkCanSend
{
    if ([TSTools isEmpty:[self getContentByTitle:@"标题:"]]) {
        [TSTools showAlert:@"请输入标题"];
        return false;
    }
//    if ([TSTools isEmpty:[self getContentByTitle:@"内容:"]]) {
//        [TSTools showAlert:@"请输入内容"];
//        return false;
//    }
    if ([TSTools isEmpty:[self getContentByTitle:@"接收人:"]]) {
        [TSTools showAlert:@"请选择接收人"];
        return false;
    }
    if ([TSTools isEmpty:[self getContentByTitle:@"审核人:"]]) {
        [TSTools showAlert:@"请选择审核人"];
        return false;
    }
    return true;
    
}

- (void)updateMsg
{
    WS(weakSelf);
    NSString *minites_str = [self getContentByTitle:@"时限:"];
    msgModel.requestParams = @{TSDictionaryKeyDefine_Id:msgId, @"title":[self getContentByTitle:@"标题:"], @"messageData":[self getContentByTitle:@"内容:"], @"time":[self getContentByTitle:@"时间:"], @"place":[self getContentByTitle:@"地点:"], @"sender":[self getContentByTitle:@"发送人:"], @"timeLimit":[NSString stringWithFormat:@"%zd", minites_str.integerValue],TSDictionaryKeyDefine_MessageType:[self getMessageType]};
    [msgModel fetchWithPath:kRequestUrl_SendMessage_update completionHandler:^(BOOL isSucceeded, NSError *error) {
        if (!weakSelf) {
            return;
        }
        
        if (isSucceeded) {
            [[LBToastManager manager] showtoast:@"修改成功!"];
            
            [weakSelf.navigationController popViewControllerAnimated:YES];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:TSNotification_MessageChangeSucceeded object:nil];
        }
        else{
            [[LBToastManager manager] showtoast:@"修改失败!"];
        }
        
    } NoProgress:NO];
}

-(NSString *)getMessageType
{
    return [[self getContentByTitle:@"类型:"] isEqualToString:@"通知"]?@"1":@"2";
}
- (void)insertMsg
{
    WS(weakSelf);
    NSString *minites_str = [self getContentByTitle:@"时限:"];
    NSString *type = [self getMessageType];
    msgModel.requestParams = @{TSDictionaryKeyDefine_Title:[self getContentByTitle:@"标题:"], TSDictionaryKeyDefine_MessageData:[self getContentByTitle:@"内容:"], TSDictionaryKeyDefine_Time:[self getContentByTitle:@"时间:"], TSDictionaryKeyDefine_Place:[self getContentByTitle:@"地点:"], TSDictionaryKeyDefine_Sender:[self getContentByTitle:@"发送人:"], TSDictionaryKeyDefine_Recipient:[self getContentByTitle:@"接收人:"], TSDictionaryKeyDefine_Audit:[self getContentByTitle:@"审核人:"], TSDictionaryKeyDefine_TimeLimit:[NSString stringWithFormat:@"%zd", minites_str.integerValue],
        TSDictionaryKeyDefine_MessageType:type};
    
    if(self.enclosurePath!=nil){
        [msgModel uploadFileWithPath:kRequestUrl_SendMessage_Insert filePath:self.enclosurePath completionHandler:^(BOOL isSucceeded, NSError *error) {
            if (!weakSelf) {
                return;
            }
            
            if (isSucceeded) {
                [[LBToastManager manager] showtoast:@"发布成功!"];
                [weakSelf dismissViewControllerAnimated:YES completion:nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:TSNotification_MessagePostSucceeded object:nil];
            }
            else{
                [[LBToastManager manager] showtoast:@"发布失败!"];
            }
        }];
    }else{
        
        [msgModel fetchWithPath:kRequestUrl_SendMessage_Insert completionHandler:^(BOOL isSucceeded, NSError *error) {
            if (!weakSelf) {
                return;
            }
            
            if (isSucceeded) {
                [[LBToastManager manager] showtoast:@"发布成功!"];
                
                [weakSelf dismissViewControllerAnimated:YES completion:nil];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:TSNotification_MessagePostSucceeded object:nil];
            }
            else{
                [[LBToastManager manager] showtoast:@"发布失败!"];
            }
            
        } NoProgress:NO];
    }
}

- (NSString *)getContentByTitle:(NSString *)title
{
    //    @[@"标题:", @"时间:", @"地点:", @"内容:", @"发送人:", @"接收人:", @"审核人:", @"附件:", @"时限:"];
    
    NSString *content = @"";
    UITableViewCell *cell = [tableView getCellByTitle:title];
    
    if ([cell isKindOfClass:[TSMsgContentItemCell class]]) {
        TSMsgContentItemCell *item_cell = (TSMsgContentItemCell *)cell;
        content = item_cell.contentTextField.text;
    }
    else if ([cell isKindOfClass:[TSMsgDatePickerTextFieldCell class]]){
        TSMsgDatePickerTextFieldCell *date_cell = (TSMsgDatePickerTextFieldCell *)cell;
        
        content = [NSString stringWithFormat:@"%f", date_cell.contentTextField.datePicker.date.timeIntervalSince1970];
    }
    else if ([cell isKindOfClass:[TSPickerViewTextFieldCell class]]){
        TSPickerViewTextFieldCell *picker_cell = (TSPickerViewTextFieldCell *)cell;
        content = picker_cell.contentTextField.text;
    }
    return content;
}

- (void)presentViewController:(NSNotification *)noti
{
    NSNumber *type = noti.object;
    if(type.integerValue == ToolBarTextField_Type_Content){
        TSEditContentController *edit_vc = [[TSEditContentController alloc] init];
        TSBaseNavigationController *nav = [[TSBaseNavigationController alloc] initWithRootViewController:edit_vc];
        edit_vc.content = [self getContentByTitle:@"内容:"];
        [self presentViewController:nav animated:YES completion:nil];
    }else{
        TSMutipleCheckTableViewController *multiple_vc = [[TSMutipleCheckTableViewController alloc] init];
        multiple_vc.toolBarTextFieldType = type.integerValue;
        TSBaseNavigationController *nav = [[TSBaseNavigationController alloc] initWithRootViewController:multiple_vc];
        [self presentViewController:nav animated:YES completion:nil];
    }
    
}

-(void)selectedEnclosure:(NSNotification *)noti
{
    self.enclosurePath = noti.object;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
